#! /bin/bash
# You need to have an already created vm, and use this vm to create other templates.

domain=$1
num=$2
work_dir=/vms


replace_domain() {
  echo replace_domain  
}

check_empty() {
  str=$1
  output=$2
  if [ -z $str ]; then
    echo $output
    exit 1
  fi
}

generate_xml() {
  echo genrate xml.
  virsh dumpxml $domain > $work_dir/temp.xml
  for i in $(seq 1 $num); do
    echo replace vm domain.
    sed "s/${domain}/${domain}-${i}/g" temp.xml > $work_dir/${domain}-${i}.xml

    echo replace uuid.
    uuid=$(grep uuid ${domain}-${i}.xml | grep "<uuid>.*</uuid>" | sed "s/<uuid>//g" | sed "s/<\/uuid>//g")
    uuid=$(echo $uuid | sed 's/-/\\-/g')
    new_uuid=$(cat /proc/sys/kernel/random/uuid)
    check_empty $uuid "uuid is empty"
    check_empty $new_uuid "new_uuid is empty"
    sed -i "s/${uuid}/${new_uuid}/g" $work_dir/${domain}-${i}.xml 

    echo replace mac.
    mac=$(grep "mac add" $work_dir/${domain}-${i}.xml | sed "s/<mac address='//g" | sed "s/\/>//g" | sed "s/'//g")
    cut_position=$(echo $mac | cut -d':' -f4)
    prefix_mac=$(echo $mac | awk -F${cut_position} '{print $1}')
    suffix_mac=$(openssl rand -hex 3 | sed 's/\(..\)/\1:/g; s/.$//')
    mac=$(echo $mac | sed 's/:/\\:/g')
    echo $prefix_mac, $suffix_mac $mac $(grep mac $work_dir/${domain}-${i}.xml)
    sed -i "s/${mac}/${prefix_mac}${suffix_mac}/g" $work_dir/${domain}-${i}.xml

    echo replace qcow2 file.
    diskpath=$(grep "source file" $work_dir/${domain}-${i}.xml | sed "s/<source file='//g" | sed "s/\/>//g" | sed "s/'//g")
    diskpath=$(echo $diskpath | awk -F/ '{print $NF}')
    vm_name=$(echo $diskpath | awk -F. '{print $1}')
    extended_name=$(echo $diskpath | awk -F. '{print $NF}')
    sed -i "s/${diskpath}/${vm_name}.${extended_name}/g" $work_dir/${domain}-${i}.xml
  done

}

copy_img() {
  echo copy qcow2.
  diskpath=$(grep "source file" /vms/temp.xml | sed "s/<source file='//g" | sed "s/\/>//g" | sed "s/'//g")
  for i in $(seq 1 $num); do
    if [ -f ${work_dir}/${domain}-${i}.qcow2 ]; then
      rm -f ${work_dir}/${domain}-${i}.qcow2
    fi
    cp $diskpath ${work_dir}/${domain}-${i}.qcow2
  done
}

import_domain() {
  for i in $(seq 1 $num); do
    virsh define $work_dir/${domain}-${i}.xml 
  done
}

main() {
  generate_xml
  copy_img
  import_domain
}

main
